<?php

class DefaultController extends Controller_index
{
	public function actionIndex()
	{   
	        $votemodel =  Vote::model()->findByPk(1);
            $connection = Yii::app()->db;
            //全部
            $sql_1 = "select count(*) as count from users order by number desc,id";  
            $command_1=$connection->createCommand($sql_1); 
            $res_1 = $command_1->queryAll(); 
            $count_1=$res_1[0]['count'];
            //最新
            $sql_2 = "select count(*) as count from users order by add_time desc";  
            $command_2=$connection->createCommand($sql_2); 
            $res_2 = $command_2->queryAll(); 
            $count_2=$res_2[0]['count'];
            //
            $model2=Users::model()->findAll(array(
                    'condition' => 'is_check=1',
                    'order' => 'add_time desc',
                    'limit' =>10
                ));
            $model=Users::model()->findAll(array(
                    'condition' => 'is_check=1',
                    'order' => 'number desc,id',
                    'limit' =>10
            ));
            shuffle($model);
            $this->render('index',array(
                       'model'=>$model,
                       'votemodel' =>$votemodel,
                       'model2'=>$model2,
                       'count_1'=>$count_1,
                       'count_2'=>$count_2,
                       'number_1'=>10,
                       'number_2'=>10,
            ));
	}
        public function actionLoadMore(){
            if(isset($_POST['number'])){
                $connection = Yii::app()->db;  
                $number=$_POST['number'];
                $sql="select * from users where is_check=1 order by number desc,id limit ".$number.",10";
                $command = $connection->createCommand($sql);  
                $data = $command->queryAll();  
                shuffle($data);
                echo CJSON::encode($data);
            }            
        }
        public function actionLoadMore2(){
            if(isset($_POST['number'])){
                $connection = Yii::app()->db;  
                $number=$_POST['number'];
                $sql="select * from users where is_check=1 order by add_time desc limit ".$number.",10";
                $command = $connection->createCommand($sql);  
                $data = $command->queryAll();  
                echo CJSON::encode($data);
            }            
        }
        public function actionSearch()
	{
                $model=new Vote();
                $this->render('search',array(
                       'model'=>$model,
               ));
	}
        
        public function actionTop()
	{
                $model=new Users();
                $model=$model->findAll(" 1=1 order by number desc");
                $this->render('top',array(
                       'model'=>$model,
               ));
	}
        
        public function actionRegister()
	{
                $model=new Users;
                $model->setScenario('register');     
		//如果前台开启ajax则取消此注释
		//$this->performAjaxValidation($model);

		if(isset($_POST['Users']))
		{
			$model->attributes=$_POST['Users'];
                        $model->add_time=date('Y-m-d H:i:s',time());
                        $model->number=0;
                        $model->is_check=0;
                        
                        
                        $uploadedimage=CUploadedFile::getInstance($model, 'head_image');

                        //图片大小
                        if(isset($uploadedimage)){
                            $img_siz=$uploadedimage->size;
                            if($img_siz<=0){
                                Yii::app()->user->setFlash('imgage_error','图片应小于500kb。');
                                $this->render('register',array(
                                       'model'=>$model,
                               ));                           
                                return;                               
                            }
                            $type=$uploadedimage->type;
                            $array_img = array("jpg", "jpeg", "gif", "png");
                            $arr = explode("/",$type);
                            if(!in_array($arr[1],$array_img)){
                                Yii::app()->user->setFlash('imgage_type_error','图片格式必须为jpg, jpeg, gif, png 其中之一。');
                                $this->render('register',array(
                                       'model'=>$model,
                                )); 
                                return;
                            }
                            if($img_siz>512000){
                                Yii::app()->user->setFlash('imgage_error','图片应小于500kb。');
                                $this->render('register',array(
                                       'model'=>$model,
                               ));                           
                                return;
                            }                            
                        }
                        $uploaddir=Yii::app()->basePath . '/../uploads/';

                        if(is_object($uploadedimage) && get_class($uploadedimage)==='CUploadedFile')
                        {
                        $filename = md5(uniqid());
                        $ext = $uploadedimage->extensionName;
                        $uploadfile=$uploaddir . $filename . '.' . $ext;
                        $uploadedimage->saveAs($uploadfile);
                        $model->head_image=Yii::app()->baseUrl.'/uploads/' . $filename . '.' . $ext;
                        } 
                        //要判断是不是重复注册
			if($model->save()){
                            Yii::app()->user->setFlash('success','操作成功！');
                            $this->redirect(array('default/register'));
                        }
		}
                $this->render('register',array(
                       'model'=>$model,
               ));
	}
        
        public function actionChildren_msg($id)
	{
                $model=Users::model()->findByPk($id);
                $connection = Yii::app()->db;  
                $sql = "select id,rowno,number from (select id,number,(@rowno:=@rowno+1) as rowno from users,(select (@rowno:=0)) b order by number desc) c where id= ".$id;  
                $command = $connection->createCommand($sql);  
                $result = $command->queryAll();  
                $row=$result[0]['rowno'];         
                $this->render('children_msg',array(
                       'model'=>$model,
                       'row'=>$row,
               ));
	}

        public function actionSelect(){             
                $model=new Users();
                $index=0;
                $this->render('select',array(
                    'model'=>$model,
                    'index'=>$index,    
               ));       
        }
        /**
         * 搜索
         */
        public function actionSelectMsg(){
            if(isset($_POST['username'])){
                $type=$_POST['type'];
                $connection = Yii::app()->db;  
                if($type==1){
                    $sql="SELECT * FROM users WHERE is_check=1 AND id=".$_POST['username'];
                }else{
                    $sql="SELECT * FROM users WHERE is_check=1 AND username LIKE '%".$_POST['username']."%'";
                }
//                $sql="SELECT * FROM users WHERE username LIKE '%".$_POST['username']."%'";
                $command = $connection->createCommand($sql);  
                $data = $command->queryAll();  
                echo CJSON::encode($data);
            }

        }
        /**
         * 搜索
         */
        public function actionSelectIndex() {
            if(isset($_GET['username'])){
                $index=1;
                $type=$_GET['type'];
                if($type==1){
                   $model=Users::model()->findAll("is_check=1 and id=".$_GET['username']); 
                }else{
                    $model=Users::model()->findAll("is_check=1 and username LIKE '%".$_GET['username']."%'");
                }
                $this->render('select',array(
                    'model'=>$model,
                    'index'=>$index,
                    'username'=>$_GET['username'],
		));
            }
        }
        /**
         * 投票
         */
        public function actionSet_vote(){
            if(isset($_POST['id'])){
                $uid=$_POST['id'];
//                $vote_id=$_POST['vote_id'];
                $users=Users::model()->findByPk($uid);
                $vote_id=$users->vote_id;
                //获取ip
                $ip=Yii::app()->request->userHostAddress;
                $openid = $_POST['openid'];
                $app_user_id = $_POST['app_user_id'];
                $vote=Vote::model()->findByPk($vote_id);
                //投票开始结束日期
                $start_date=$vote->start_date;
                $end_date=$vote->end_date;
                $add_time=date('y-m-d H:i:s',time());  
                if(strtotime($add_time)<strtotime($start_date)){
                    echo '活动未开始无法投票';
                    return;                    
                }
                if(strtotime($add_time)>strtotime($end_date)){
                    echo '活动已结束无法投票';
                    return;                    
                }                
                //投票规则
                $connection = Yii::app()->db;  
                $spacing=$vote->spacing;
                $vote_num=$vote->number;
                //获取该时间段投票次数 
                //$new_date = date('Y-m-d H:i:s',strtotime('-'.$spacing.' min',strtotime($add_time)));
                $new_date = date('Y-m-d').' 00:00:00';
                //设备号openid限定
                $sql="select COUNT(*) as count from history where openid='".$openid."' and add_time>='".$new_date."' and add_time<='".$add_time."'";
                
                $command_1=$connection->createCommand($sql);
                $res = $command_1->queryAll();

                $votecount= isset($res[0]['count'])?$res[0]['count']:0;
                if($votecount>=3){
                    echo '每天只能投三票。谢谢。';
                    return;
                }
                //app用户id限定
                $sql="select COUNT(*) as count from history where app_user_id='".$app_user_id."' and add_time>='".$new_date."' and add_time<='".$add_time."'";
                
                $command_1=$connection->createCommand($sql);
                $res = $command_1->queryAll();

                $votecount= isset($res[0]['count'])?$res[0]['count']:0;
                if($votecount>=3){
                    echo '每天只能投三票。谢谢。';
                    return;
                }
                //设备号openid和参与对象id限定
                $sql1="select COUNT(*) as count from history where openid='".$openid."' and users_id='".$uid."' and add_time>='".$new_date."' and add_time<='".$add_time."'";
                $command_2=$connection->createCommand($sql1); 
                $res1 = $command_2->queryAll(); 
                $v_count=$res1[0]['count'];
                if($v_count>=$vote_num){
                    echo '每天一栏只能投一票，谢谢。';
                    return;
                } 
                //app用户id和参与对象id限定
                $sql1="select COUNT(*) as count from history where app_user_id='".$app_user_id."' and users_id='".$uid."' and add_time>='".$new_date."' and add_time<='".$add_time."'";
                $command_2=$connection->createCommand($sql1); 
                $res1 = $command_2->queryAll(); 
                $v_count=$res1[0]['count'];
                if($v_count>=$vote_num){
                    echo '每天一栏只能投一票，谢谢。';
                    return;
                } 
                //投票数加一
                $model=Users::model()->findByPk($uid);
                $number=$model->number;
                $number+=1;
                Users::model()->updateByPk($uid,array('number'=>$number));
                $date=date('y-m-d H:i:s',time());                
                $sql="insert into history (vote_id,app_user_id,openid,users_id,ip_address,add_time)values(".$vote_id.",'".$app_user_id."','".$openid."',".$uid.",'".$ip."','".$date."');";
                $command = $connection->createCommand($sql);  
                $command->query(); 

                echo '投票成功';
            }
        }
        
        public function actionMessage($id)
	{
                $model=  Vote::model()->findByPk(1);
                $str="";
                $conetnt="";
                if($id==1){
                     $str="奖品设置";
                    $conetnt=$model->a_remark;
                }else if($id==2){
                     $str="报名流程";
                     $conetnt=$model->f_remark;
                }else if($id=3){
                     $str="活动介绍"; 
                     $conetnt=$model->s_remark;
                     
                }
                $this->render('message',array(
                       'conetnt'=>$conetnt,
                       'str'=>$str,
                       'id'=>$id,
                       
               ));
	}

        /**
	 * Performs the AJAX validation.
	 * @param WxJoin $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='wx-join-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
